from inc.models import db
from inc.models import (
    JiraProject,
    JiraStage,
    JiraTask,
    AdminMember,
    JiraMember
)
from datetime import datetime
from .services import get_project_detail
from member.workflow.services import ProjectWorkflow as SystemProjectWorkflow


class ProjectWorkflow:
    @staticmethod
    def complete_project(project_id, user_id):
        """完成项目（提交结项申请）"""
        try:
            # 获取项目详情以检查权限
            project = get_project_detail(project_id, user_id)
        except PermissionError:
            raise PermissionError("只有项目负责人可以提交结项申请")

        # 检查项目状态
        if project.status != JiraProject.IN_PROGRESS:
            raise ValueError("只有进行中的项目可以提交结项申请")

        try:
            # 先完成所有未完成的任务和阶段
            for stage in project.stages:
                # 更新阶段下的任务
                for task in stage.tasks:
                    if task.status != JiraTask.COMPLETED:
                        task.status = JiraTask.COMPLETED
                        task.completed_at = datetime.now()

                # 更新阶段状态
                if stage.status != JiraStage.COMPLETED:
                    stage.status = JiraStage.COMPLETED
                    stage.completed_at = datetime.now()

            # 提交任务和阶段的更新
            db.session.commit()

            # 然后请求项目结项
            SystemProjectWorkflow.request_project_closure(project_id, user_id)

            return {"status": "success", "message": "项目已提交结项申请，等待第一审批人审核"}

        except Exception as e:
            db.session.rollback()
            raise e